﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla.Rules.CommonRules;
using Csla.Core;
using System.Collections;

namespace NetFrameworkExtensions.BusinessLayer.Csla4.Rules
{
  public class NonDuplicatePropertyRule : CommonBusinessRule
  {
    public NonDuplicatePropertyRule(IPropertyInfo primaryProperty, IEqualityComparer comparer = null)
      : base(primaryProperty)
    {
      Comparer = comparer ?? EqualityComparer<object>.Default;
    }

    public IEqualityComparer Comparer { get; private set; }

    protected override void Execute(Csla.Rules.RuleContext context)
    {
      var bb = context.Target as BusinessBase;
      if (bb == null) return;

      var currentValue = this.ReadProperty(context.Target, PrimaryProperty);
      if (currentValue == null) return;

      var parent = bb.Parent as IEnumerable;
      if (parent == null) return;

      foreach (var sibling in parent)
      {
        if (sibling != bb)
        {
          var siblingValue = ReadProperty(sibling, PrimaryProperty);
          if (siblingValue != null)
          {
            if (Comparer.Equals(currentValue, siblingValue))
            {
              // TODO: ISK poner en recursos
              context.AddErrorResult("El valor está repetido", true);
              break;
            }
          }
        }
      }
      //context.Target
      base.Execute(context);
    }
  }
}
